# coding: utf8
import logging as log
import uuid

import tornado

import cms_config
from app.base_controller import BaseController
from app.common import global_space
from app.models import AppUser
from libs.util import check_param

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


# /api/login
class Login(BaseController):

    @tornado.web.asynchronous
    def post(self):
        http = tornado.httpclient.AsyncHTTPClient()
        code = self.get_json_argument("code", '')
        remote_ip = self.request.remote_ip
        param = [code, ]
        log.info(code)
        log.info(remote_ip)
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        http.fetch(
            "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code".format(cms_config.app_id, cms_config.app_secret, code),
            callback=self.on_response)

    def on_response(self, response):
        if response.error:
            self.render_json(code=1002, msg='系统异常')
        else:
            json = tornado.escape.json_decode(response.body)

            session = uuid.uuid1().hex
            global_space.set_session(session, json, 21600)
            # log.info(type(json))
            # log.info(json)
            avatar_url = self.get_json_argument("avatarUrl", '')
            city = self.get_json_argument("city", '')
            country = self.get_json_argument("country", '')
            gender = self.get_json_argument("gender", 1)
            language = self.get_json_argument("language", '')
            nick_name = self.get_json_argument("nickName", '')
            province = self.get_json_argument("province", '')
            # log.info(city)
            if not json.get('openid', ''):
                self.render_json(code=1002, msg='系统异常')
                return
            AppUser.objects.update_or_create(openid=json['openid'], defaults={'avatarUrl': avatar_url, 'city': city,
                                                                              'country': country, 'gender': gender, 'language': language, 'nickName': nick_name, 'province': province})

            self.render_json(data={'session_id': session})
